Lists | Listas

O que é uma lista?

Uma estrutura de dados heterogenia mutável que preserva ordem dos elementos.

O que eu quero dizer por heterogenia?

2 ou mais diferentes tipos de dados podem estar simultaneamente na lista

O que eu quero dizer por mutável?

Os dados podem ser alterados depois da criação da lista

O que eu quero dizer por preservar ordem?

Os dados permanecem na mesma ordem de sua criação, concatenação, enfim

Exemplos de Listas


In [1]:
[] # empty list


Out[1]:
[]

In [2]:
type([])


Out[2]:
list

In [3]:
[1, 2, 3, 4] # list of integers


Out[3]:
[1, 2, 3, 4]

In [4]:
['a', 'b', 'c', 'b'] # list of strs


Out[4]:
['a', 'b', 'c', 'b']

In [5]:
[1, 2, 'a', 'b', [42, 6/7, 'text']] # mixed lists


Out[5]:
[1, 2, 'a', 'b', [42, 0.8571428571428571, 'text']]

Como criar listas

Exemplo não pythonico de se criar uma Lista


In [2]:
lst = []
for i in range(10):
    if i % 2:
        lst.append(i)

print(lst)


[1, 3, 5, 7, 9]

In [8]:
list(range(10))


Out[8]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

List Comprehension


In [9]:
[1 for i in range(10)]


Out[9]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

In [10]:
[i for i in range(10) if i % 2]


Out[10]:
[1, 3, 5, 7, 9]

In [11]:
[i ** 2 for i in range(10) if i % 2]


Out[11]:
[1, 9, 25, 49, 81]

In [12]:
["red" if i % 2 else "blue" for i in range(10)]


Out[12]:
['blue', 'red', 'blue', 'red', 'blue', 'red', 'blue', 'red', 'blue', 'red']

In [13]:
["red" if i % 2 else "blue" for i in range(10) if i > 5]


Out[13]:
['blue', 'red', 'blue', 'red']

Métodos Built-in


In [6]:
dir(list) # Available methods


Out[6]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

In [6]:
lst = [i for i in range(10) if i % 2] # odd numbers

lst.append(0xc0ffee)
lst


Out[6]:
[1, 3, 5, 7, 9, 12648430]

In [5]:
lst = [i for i in range(10) if i % 2] # odd numbers
new_lst = [i for i in range(10) if i % 2 == 0] # even numbers

lst.extend(new_lst)
lst


Out[5]:
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]

Verificando pertinência


In [14]:
lst = [1, 3, 5, 7, 9]

In [15]:
1 in lst


Out[15]:
True

In [16]:
4 in lst


Out[16]:
False

Obtendo o Index de determinado elemento


In [7]:
lst = [1, 3, 5, 7, 9]

In [8]:
lst.index(1) # The first element has index 0


Out[8]:
0

In [9]:
lst.count(3) # How many time the given element appear in such list?


Out[9]:
1

In [10]:
lst.count(4)


Out[10]:
0

In [11]:
#lst.index(4)

#---------------------------------------------------------------------------
#ValueError                                Traceback (most recent call last)
#<ipython-input-14-9e4c9bbba08f> in <module>()
#----> 1 lst.index(4)
#
#ValueError: 4 is not in list

In [21]:
sum(lst) # Sum of each element


Out[21]:
25

In [22]:
min(lst)


Out[22]:
1

In [23]:
max(lst)


Out[23]:
9

In [24]:
len(lst)


Out[24]:
5

In [25]:
for i in lst:
    print(i, end=' ')


1 3 5 7 9 

In [26]:
for i in lst:
    i *= 2

In [27]:
lst


Out[27]:
[1, 3, 5, 7, 9]

In [28]:
lst * 2


Out[28]:
[1, 3, 5, 7, 9, 1, 3, 5, 7, 9]

In [29]:
#lst + 2

#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-24-33a94180b36b> in <module>()
#----> 1 lst + 2
#
#TypeError: can only concatenate list (not "int") to list

In [30]:
for i in range(len(lst)):
    lst[i] *= 2
lst


Out[30]:
[2, 6, 10, 14, 18]

In [31]:
lst1 = [i for i in range(10) if i % 2]
lst1


Out[31]:
[1, 3, 5, 7, 9]

In [32]:
lst2 = [i * 2 for i in range(10) if i % 2]
lst2


Out[32]:
[2, 6, 10, 14, 18]

In [33]:
lst == lst2


Out[33]:
True

In [34]:
lst is lst2


Out[34]:
False

In [35]:
lst3 = [0] * len(lst1)

for index, value in enumerate(lst1):
    lst3[index] = value * 2
lst3


Out[35]:
[2, 6, 10, 14, 18]

In [36]:
# slicing
lst


Out[36]:
[2, 6, 10, 14, 18]

In [37]:
lst[1:2]


Out[37]:
[6]

In [38]:
lst[:2]


Out[38]:
[2, 6]

In [39]:
lst[1:]


Out[39]:
[6, 10, 14, 18]

In [40]:
lst[:-1]


Out[40]:
[2, 6, 10, 14]

In [41]:
lst[::-1]


Out[41]:
[18, 14, 10, 6, 2]

In [42]:
# indexing
lst


Out[42]:
[2, 6, 10, 14, 18]

In [43]:
len(lst)


Out[43]:
5

In [44]:
lst[0]


Out[44]:
2

In [45]:
lst[len(lst) -1]


Out[45]:
18

In [46]:
lst[-1]


Out[46]:
18

In [47]:
lst[-2]


Out[47]:
14

In [48]:
#lst[13]

#---------------------------------------------------------------------------
#IndexError                                Traceback (most recent call last)
#<ipython-input-44-148af8a65684> in <module>()
#----> 1 lst[13]
#
#IndexError: list index out of range

In [49]:
#lst[-9]

#---------------------------------------------------------------------------
#IndexError                                Traceback (most recent call last)
#<ipython-input-45-1b205bc9ac28> in <module>()
#----> 1 lst[-9]
#
#IndexError: list index out of range

In [50]:
#lst[1, 3]

#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-46-b9ef5c5bd789> in <module>()
#----> 1 lst[1, 3]
#
#TypeError: list indices must be integers or slices, not tuple

In [51]:
#lst > 3

#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-47-95398925f275> in <module>()
#----> 1 lst > 3
#
#TypeError: unorderable types: list() > int()

In [52]:
lst1


Out[52]:
[1, 3, 5, 7, 9]

In [53]:
lst2


Out[53]:
[2, 6, 10, 14, 18]

In [54]:
lst1 + lst2


Out[54]:
[1, 3, 5, 7, 9, 2, 6, 10, 14, 18]

In [55]:
#lst1 * lst2

#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-79-67c3fb65c435> in <module>()
#----> 1 lst1 * lst2
#
#TypeError: can't multiply sequence by non-int of type 'list'

In [56]:
lst


Out[56]:
[2, 6, 10, 14, 18]

In [57]:
lst1 = [True if _ > 10 else False for _ in lst]
lst1


Out[57]:
[False, False, False, True, True]

In [58]:
#lst[l1]

#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-82-4bb6def646de> in <module>()
#----> 1 lst[lst1]
#
#TypeError: list indices must be integers or slices, not list

In [59]:
lst1 = lst

In [60]:
id(lst)


Out[60]:
140508654019016

In [61]:
id(lst1)


Out[61]:
140508654019016

In [62]:
lst1[2] = .79

In [63]:
lst


Out[63]:
[2, 6, 0.79, 14, 18]

In [64]:
lst1 = lst.copy()

In [65]:
id(lst1)


Out[65]:
140508654127560

In [66]:
lst1[2] = 379

In [67]:
lst1


Out[67]:
[2, 6, 379, 14, 18]

In [68]:
lst


Out[68]:
[2, 6, 0.79, 14, 18]

In [69]:
lst1 = lst[:]

In [71]:
id(lst1)


Out[71]:
140508713976456

In [73]:
lst is lst1


Out[73]:
False

In [74]:
lst


Out[74]:
[2, 6, 0.79, 14, 18]

In [75]:
list(map(lambda x: x * 2, lst))


Out[75]:
[4, 12, 1.58, 28, 36]

In [76]:
lst = list(range(10))

In [77]:
lst.remove(2)

In [78]:
lst


Out[78]:
[0, 1, 3, 4, 5, 6, 7, 8, 9]

In [79]:
#lst.remove(-1)

#---------------------------------------------------------------------------
#ValueError                                Traceback (most recent call last)
#<ipython-input-6-9cb22bf5b017> in <module>()
#----> 1 lst.remove(-1)
#
#ValueError: list.remove(x): x not in list

In [80]:
del lst # Deleting the whole list

In [82]:
#lst

#---------------------------------------------------------------------------
#NameError                                 Traceback (most recent call last)
#<ipython-input-11-12f54a96f644> in <module>()
#----> 1 lst
#
#NameError: name 'lst' is not defined

In [88]:
#lst = list(range(10))
#lst[len(lst)] = 'new_value'

#---------------------------------------------------------------------------
#IndexError                                Traceback (most recent call last)
#<ipython-input-87-c4d3abf378eb> in <module>()
#      1 lst = list(range(10))
#----> 2 lst[len(lst)] = 'new_value'
#
#IndexError: list assignment index out of range

In [90]:
lst = list(range(10))

lst[1:6] = ['a', 'b', 'c', 'd', 'e']
lst


Out[90]:
[0, 'a', 'b', 'c', 'd', 'e', 6, 7, 8, 9]